package com.usefullc.proxy.test.http.test;

import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import javax.sound.midi.Soundbank;
import java.nio.ByteBuffer;

public class RelayHandler extends ChannelInboundHandlerAdapter {
    private Channel remoteChannel;
    private boolean local = false;

    public RelayHandler(Channel remoteChannel,boolean local) {
        this.remoteChannel = remoteChannel;
        this.local = local;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.err.println("流量来源："+ctx+",流量去向："+remoteChannel);

        ByteBuf byteBuf = (ByteBuf) msg;
        ByteBuffer copyByteBuf = ByteBuffer.allocate(byteBuf.writerIndex());
        byteBuf.getBytes(0,copyByteBuf);
        char[] chars = HexUtil.encodeHex(copyByteBuf.array());
        System.out.println("十六进制，"+ctx);
        for (int i = 0; i < chars.length; i+=2) {
            System.out.print(chars[i]+""+chars[i+1]+" ");
        }
        System.out.println();
        remoteChannel.writeAndFlush(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        flushAndClose(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        /**
         * 连接断开时关闭另一端连接。
         * 如果代理到远端服务器连接断了也同时关闭代理到客户的连接。
         * 如果代理到客户端的连接断了也同时关闭代理到远端服务器的连接。
         */
        flushAndClose(remoteChannel);
    }

    private void flushAndClose(Channel ch) {
        if (ch != null && ch.isActive()) {
            ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }
}
